package com.geezdata.cps.sdk3rd.payment.pay.alipay;

import java.math.BigDecimal;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.geezdata.cps.sdk3rd.payment.constant.Constants;
import com.geezdata.cps.sdk3rd.payment.request.PayRequest;

public class AliPagePay extends AliPay {
	@Override
	public String pay(PayRequest request) {
		AlipayClient alipayClient = createAlipayClient(request.getPayConfig());
		
        String form = Constants.FAIL;
        try {
        	form = alipayClient.pageExecute(convert2AlipayPayRequest(request)).getBody();
        } catch (AlipayApiException e) {
        	e.printStackTrace();
        }
 
        return form;
	}
	
	private AlipayTradePagePayRequest convert2AlipayPayRequest(PayRequest request) {
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(request.getReturnUrl());
        alipayRequest.setNotifyUrl(request.getNotifyUrl());
        alipayRequest.setBizContent(convert2PayBizContent(request));
        return alipayRequest;
	}
	
	private String convert2PayBizContent(PayRequest request) {
		JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", request.getOutTradeNo());
        bizContent.put("total_amount", new BigDecimal(request.getTotalAmount()).divide(new BigDecimal(100)));
        bizContent.put("subject", request.getSubject());
        bizContent.put("body", request.getBody());
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
		return bizContent.toString().replaceAll("\"", "'");
	}
}
